package application.fileTransfer;

import java.util.ArrayList;

import application.chat.Constants;

public class FilePacket {
	
	/**
	 * The name of the file
	 */
	String fileName;
	/**
	 * The length of the file in bytes
	 */
	long length;
	
	/**
	 * Constructs a new FilePacket with the header given as an ArrayList of Bytes in which each byte represents a char
	 * @param header
	 */
	public FilePacket(ArrayList<Byte> header){
		fileName = new String();
		int i;
		for (i = 0; header.get(i) != '\07'; i++){
			fileName += (char)header.get(i).byteValue();
		}
		i++;
		length = length | (long)((byte)header.get(i) << 3*Constants.BYTE_LENGTH) & 0xFF000000L;
		i++;
		length = length | (long)((byte)header.get(i) << 2*Constants.BYTE_LENGTH) & 0xFF0000L;
		i++;
		length = length | (long)((byte)header.get(i) << 1*Constants.BYTE_LENGTH) & 0xFF00L;
		i++;
		length = length | (long)(byte)header.get(i) & 0xFFL;
		if(fileName.contains("\\")){
		fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
		}
	}
	/**
	 * Constructs a new FilePacket with a given filename and length
	 * @param fileName
	 * @param length
	 */
	public FilePacket(String fileName, int length){
		this.fileName = fileName;
		this.length = length;
	}
	
	
	/**
	 * Returns the fileName of this packet
	 * @return The fileName
	 */
	public String getFileName(){
		return fileName;
	}
	/**
	 * Returns the length of this packet
	 * @return The length of this packet
	 */
	public long getLength(){
		return this.length;
	}
	/**
	 * Returns this header in a readable String form
	 */
	public String toString(){
		String result = new String();
		result += fileName;
		result += '\07';
		result += (char)((char)(length >> 3*Constants.BYTE_LENGTH)& 0x00FF);
		result += (char)((char)(length >> 2*Constants.BYTE_LENGTH)& 0x00FF);
		result += (char)((char)(length >> 1*Constants.BYTE_LENGTH)& 0x00FF);
		result += (char)((char)length & 0x00FF);
		char k = (char)((char)length & 0x00FF);
		int j = (int)k;
		System.out.println((char)138);
		System.out.println((int)(char)138);
		return result;
	}
	/**
	 * Returns the header in an byte array in which each byte represents a char
	 * @return The header in byte array form
	 */
	public byte[] toByteArray(){
		byte[] result = new byte[fileName.length() + 5];
		int i;
		for (i = 0; i < fileName.length(); i++){
			result[i] = (byte)fileName.charAt(i);
		}
		result[i] = (byte)Constants.DELIMITER;
		i++;
		result[i] = (byte)(length >> 3*Constants.BYTE_LENGTH);
		i++;
		result[i] = (byte)(length >> 2*Constants.BYTE_LENGTH);
		i++;
		result[i] = (byte)(length >> 1*Constants.BYTE_LENGTH);
		i++;
		result[i] = (byte)(length);
		return result;
	}

}
